import { getListApi, reverseApprovalApi, statisticsDataApi, receivableFeeExcelApi } from "@/api/financialManagement/receivable";
import { message } from "ant-design-vue";
import dayjs from "dayjs";
import { Ref, computed } from "vue";
export default function OperationHook(state: {
  searchForm: ReceivableFee.SearchForm;
  tableData: Ref<ReceivableFee.ListRows[]>;
  tableRef: Ref<any>;
  dialogOpts: Base.DialogOpts;
  drawerOpts: Base.DrawerOpts;
  loading: Ref<boolean>;
}) {
  const { searchForm, tableData, loading, tableRef, dialogOpts } = state;
  const selectRows = computed<Array<ClientWaybillManagement.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const selectAmount = computed<number>(() => {
    const allAmount = selectRows.value.map((t: any) => t.receivablePrice || 0);
    return allAmount.reduce((a: number, b: number) => ((a + b) * 100) / 100, 0).toFixed(2);
  });
  const getData = async () => {
    const params = {
      ...getParams()
    };
    loading.value = true;
    tableData.value = [];
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.beforePageNum = searchForm.pageNum;
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const { waybillNums, customerNames, customerIdList, bizIdList, finIdList, followId, accountPeriodIdList, depositTime, pageNum, pageSize, companyIdList, companyNames } = searchForm;
    const params: any = {
      preOrderNoList: [],
      waybillNumList: [],
      fbaNumberList: [],
      customerIdList,
      bizIdList,
      followId,
      finIdList,
      accountPeriodIdList,
      startDepositTime: depositTime.length ? dayjs(depositTime[0]).format("YYYY-MM-DD HH:mm:ss") : "",
      endDepositTime: depositTime.length ? dayjs(depositTime[1]).format("YYYY-MM-DD HH:mm:ss") : "",
      pageNum,
      pageSize,
      companyIdList
    };
    if (waybillNums)
      params.waybillNums = waybillNums
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (customerNames)
      params.customerNames = customerNames
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (companyNames) {
      params.companyNames = companyNames
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    }
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }

    return params;
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    getData();
  };
  // 反审核
  const reverseApprovalHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选至少一条费用！");
    return reverseApprovalApi({ ids: selectRows.value.map((t: any) => t.id) }).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("反审核成功!");
        getData();
      }
    });
  };
  // 生成对账单
  const createBillHandle = () => {
    if (!selectRows.value.length) return message.error("请勾选至少一条费用！");
    dialogOpts.title = `生成对账单`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "CreateBill";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 预览
  const previewFeeHandle = () => {
    dialogOpts.title = `预览`;
    dialogOpts.width = "1200px";
    dialogOpts.type = 1;
    dialogOpts.component = "PreviewFee";
    dialogOpts.passData = selectRows.value;
    dialogOpts.visible = true;
  };
  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams()
    };
    if (selectRows.value.length) params.list = selectRows.value;
    return statisticsDataApi(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "920px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  // 导出
  const downloadDataHandle = () => {
    const params = {
      ...getParams(),
      list: selectRows.value.length ? selectRows.value : undefined
    };

    return receivableFeeExcelApi(params).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("创建任务成功，请前往导出中心下载！");
      }
    });
  };

  return {
    searchHandle,
    getData,
    reverseApprovalHandle,
    createBillHandle,
    selectAmount,
    previewFeeHandle,
    getStatisticsDataFn,
    showStatictisHandle,
    downloadDataHandle
  };
}
